package demo.chain.exception;


import cn.hutool.core.exceptions.ValidateException;
import com.lkcoffee.demo.chain.annocation.Length;
import com.lkcoffee.demo.chain.annocation.Max;
import com.lkcoffee.demo.chain.annocation.Min;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : feixiang.li
 * @since : 2025-09-17 17:29
 */
public class Validator {


    private List<String> errorList = new ArrayList<>();


    public String getError() {
        if (errorList.size() > 0) {
            return errorList.toString();
        }
        return null;
    }

    private static ValidatorChain builder(Field field) {
        ValidatorChain validatorChain = new ValidatorChain();
        if (field.isAnnotationPresent(Max.class)) {
            Max max = field.getAnnotation(Max.class);
            validatorChain.addLast(new MaxValidatorHandler(max.value(), max.message()));
        }
        if (field.isAnnotationPresent(Min.class)) {
            Min min = field.getAnnotation(Min.class);
            validatorChain.addLast(new MinValidatorHandler(min.value(), min.message()));
        }
        if (field.isAnnotationPresent(Length.class)) {
            Length length = field.getAnnotation(Length.class);
            validatorChain.addLast(new LengthValidatorHandler(length.min(), length.max(), length.message()));
        }
        return validatorChain;
    }


    public void validate(Object obj) {
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            ValidatorChain validatorChain = builder(field);
            try {
                validatorChain.validate(field.get(obj));
                if (validatorChain.getError() != null) {
                    errorList.add(validatorChain.getError());
                }
            } catch (Exception e) {
                throw new ValidateException(e.getMessage());
            }
        }
    }


}
